<?php

namespace App\Http\Controllers\Application;

use App\Http\Controllers\Controller;
use App\Http\Requests\Application\ArearecRequest;
use App\Models\Application\Arearec;
use App\Models\Application\Page;
use App\Models\Common\EntityData\Channel\Sp;
use App\Repositories\Application\ArearecRepository;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Response;
use Validator;

class ArearecController extends Controller
{
    use ModelForm;

    /** @var  ArearecRepository */
    private $arearecRepository;

    public function __construct(ArearecRepository $arearecRepo)
    {
        $this->arearecRepository = $arearecRepo;
    }

    /**
     * Display a listing of the Arearec.
     *
     * @return Response
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('application.arearecs.index_header'));
            $content->description(__('application.arearecs.index_description'));

            $content->body($this->grid());
        });
    }

    /**
     * Show the form for creating a new Arearec.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('application.arearecs.create_header'));
            $content->description(__('application.arearecs.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created Arearec in storage.
     *
     * @param ArearecRequest $request
     *
     * @return Response
     */
    public function store(ArearecRequest $request)
    {
        $input = $request->all();

        $arearec = $this->arearecRepository->create($input);

        Flash::success(__('application.arearecs.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('application.arearecs.index'));

    }

    /**
     * Display the specified Arearec.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $arearec = $this->arearecRepository->findWithoutFail($id);

        if (empty($arearec)) {
            Flash::error(__('application.arearecs.not_found'));

            return redirect(route('application.arearecs.index'));
        }

        return view('application.arearecs.show')->with('arearec', $arearec);

    }

    /**
     * Show the form for editing the specified Arearec.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {

        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('application.arearecs.edit_header'));
            $content->description(__('application.arearecs.edit_description'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Update the specified Arearec in storage.
     *
     * @param  int              $id
     * @param ArearecRequest $request
     *
     * @return Response
     */
    public function update($id, Request $request)
    {
        $sValidators = [
            'page_id'   => 'max:100',
            'areaid'    => 'max:100',
            'subareaid' => 'max:100',
        ];
        $validators = [];

        $input = $request->all();

        // 动态判断校验
        foreach ($input as $key => $value) {
            if (isset($sValidators[$key])) {
                $validators[$key] = $sValidators[$key];
            }
        }
        // 定义校验, 没有移到request
        $validator = Validator::make($input, $validators, [
            // 'required' => ':attribute 不能为空',
        ], [
            'page_id'   => '页面',
            'areaid'    => 'area',
            'subareaid' => 'subarea',
        ]);

        // 校验
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        $arearec = $this->arearecRepository->findWithoutFail($id);

        if (empty($arearec)) {
            Flash::error(__('application.arearecs.not_found'));

            return redirect(route('application.arearecs.index'));
        }

        if (array_key_exists('_editable', $request->all())) {
            $editable                          = [];
            $editable[$request->input('name')] = $request->value;
            $arearec                           = $this->arearecRepository->update($editable, $id);
            Flash::success(__('application.arearecs.updated_success'));

            return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('application.arearecs.index'));
        }

        $arearec = $this->arearecRepository->update($input, $id);
        if (array_key_exists('_fromajax', $request->all())) {
            $url     = route('application.arearecs.index');
            return response()->json(['content' => '数据编辑成功!', 'status' => true, 'url' => $url]);
        }
        Flash::success(__('application.arearecs.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('application.arearecs.index'));
    }

    /**
     * Remove the specified Arearec from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->arearecRepository->batchDelete('id', $id)) {

                return response()->json(['message' => __('application.arearecs.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $arearec = $this->arearecRepository->findWithoutFail($id);

        if (empty($arearec)) {
            Flash::error(__('application.arearecs.not_found'));

            return redirect(route('application.arearecs.index'));
        }

        if ($flag = $this->arearecRepository->delete($id)) {

            return response()->json(['message' => __('application.arearecs.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(Arearec::class, function (Form $form) {

            $form->display('id', 'ID');
            $sps = Sp::pluck('name', 'id');
            $form->select('sp_id', 'SP')->options($sps);
            $pages = Page::pluck('name', 'id');
            $form->select('page_id', '页面')->options($pages);
            $form->text('areaid', 'area');
            $form->text('subareaid', 'subarea');
            // $form->text('data', 'data');

            // $form->display('created_at', __('base.created_at'));
            // $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid()
    {

        return Admin::grid(Arearec::class, function (Grid $grid) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');

            // // 添加按钮
            // if (!\Gate::check('application.arearecs.create')) {
            //     $grid->disableCreation();
            // }

            // // 编辑和删除按钮
            // $grid->actions(function ($actions) {
            //     // 编辑按钮
            //     if (!\Gate::check('application.arearecs.edit')) {
            //         $actions->disableEdit();
            //     }
            //     // 删除按钮
            //     if (!\Gate::check('application.arearecs.destroy')) {
            //         $actions->disableDelete();
            //     }
            // });

            // // 导出按钮
            // if (!\Gate::check('application.arearecs.export')) {
            //     $grid->disableExport();
            // }

            // // 批量操作
            // $grid->tools(function ($tools) {
            //     $tools->batch(function ($batch) {
            //         // 批量删除按钮
            //         if (!\Gate::check('application.arearecs.batch_destroy')) {
            //             $batch->disableDelete();
            //         }
            //     });
            // });

            // 添加按钮
            if (Admin::user()->cannot('application.arearecs.create')) {
                $grid->disableCreation();
            }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                $id = $actions->getKey();
                if (Admin::user()->can('application.arearecs.datas.edit_data')) {
                    // 编辑数据
                    $url = route('application.arearecs.datas.edit_data', ['arearecs' => $id]);
                    $actions->prepend('<a href ="' . $url . '" title="编辑数据"><i class="fa fa-list"></i></a>');
                }

                // 编辑按钮
                if (Admin::user()->cannot('application.arearecs.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('application.arearecs.destroy')) {
                    $actions->disableDelete();
                }
            });

            // 导出按钮
            if (Admin::user()->cannot('application.arearecs.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('application.arearecs.batch_destroy')) {
                        $batch->disableDelete();
                    }
                });
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('sp.name', 'SP')->sortable();
            $grid->column('page.name', '页面')->sortable();
            $grid->column('areaid', 'area')->sortable()->editable();
            $grid->column('subareaid', 'subarea')->sortable()->editable();
            $grid->column('data', 'data')->sortable();

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // // 禁用id查询框
                // $filter->disableIdFilter();

            });
        });
    }

    /**
     * 创建页面推荐位数据
     * @param  [type]  $id      [description]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function createAreaRecData($id, Request $request)
    {

        $arearec = $this->arearecRepository->findWithoutFail($id);

        if (empty($arearec)) {
            Flash::error(__('application.arearecs.not_found'));

            return redirect(route('application.arearecs.index'));
        }
        Admin::script('createAreaRecData(' . json_encode($arearec) . ');');
        $data['arearec'] = $arearec;
        return view('application.arearecs.create_data', $data);
    }
}
